<?php
/** Copyright 2014 TinPhp Systems, Inc.
 * @author zhangxilian 2013-8-15
 * @package TinPhp
 */
if (!defined('IN_TINPHP')) {
	exit ('Access Denied');
}
require_once(TIN_APP_PATH . 'configs/site.conf.php');
require_once(TIN_APP_PATH . 'configs/db.conf.php');
require_once(TIN_APP_PATH . 'include/TinPHP/Tin.php');
require_once(TIN_APP_PATH . 'include/TinPHP/TinBaseLogic.php');
require_once(TIN_APP_PATH . 'include/TinPHP/TinBaseView.php');
require_once(TIN_APP_PATH . 'include/TinPHP/TinMemcache.php');
require_once(TIN_APP_PATH . 'include/utils/xml.php');
require_once(TIN_APP_PATH . 'include/utils/RequestUtil.php');

/** 注册new Class 时自动加载Logic */
function autoLogic($className) {
	$classPath = TIN_APP_PATH . "app/logic/" . $className . ".php";
	if (file_exists($classPath)) {
		if (require_once($classPath)) {
		} else {
			throw new TypeException ('class ['.$className.'] not found');
		}
	}else{
		T::$tplFile = 'public/empty';
		exit('autoLogic ['.$classPath.'] not found');
	}		
}
spl_autoload_register('autoLogic');

/** TinPHP框架控制器基类；虚拟类不可实例化 */
abstract class TinAppController {
    /** TinAppConf对象 */
	public static $conf;
    /** 初始化类，加载相应配置文件 */
	public function __construct() {
		//加载主配置文件及对应ctl/、 ctl/action配置文件
		self::$conf = TinAppConf::getInstance(TIN_APP_PATH . 'configs/base.ini.php');
		self::$conf->add(TIN_APP_PATH . 'configs/' . T::$controller . '/base.ini.php');
		self::$conf->add(TIN_APP_PATH . 'configs/' . T::$controller . '/' . T::$action . '.ini.php');
		
		$web_title = $this->confValue('html_title', 'web_title');
		$ca_title = $this->confValue('html_title', T::$type."_". T::$controller.'_'.T::$action);
		T::$tpl->set("title",($ca_title ? $ca_title.'-':'').$web_title);
	}
	/** 自定义返回当前microtime时间戳 */
	public function getMicrotime(){
	    list($usec, $sec) = explode(" ", microtime());
	    return ((float)$usec + (float)$sec);
	}
	/**
	 * 设置页面输出编码
	 * @param string $charset 设置页面编码格式，默认UTF-8
	 * */
	public function setPageHeader($charset = "utf-8") {
		header('Content-type:text/html; charset=' . $charset);
	}
	/**
	 * 获取指定配置中的参数值
	 * @param string $sectionName 配置组名
	 * @param string $itemName 配置键名
	 * @return string 字符结果
	 * */
	public function confValue($sectionName, $itemName) {
		return self::$conf->confValue($sectionName, $itemName);
	}
	/**
	 * 获取指定配置中的配置组参数值
	 * @param string $sectionName 配置组名
	 * @return Array 返回数组结果
	 * */
	public function confGroup($sectionName) {
		return self::$conf->confGroup($sectionName);
	}
    /** 初始控制器方法，建议所有继承类实现 */
	function actionDefault() { }
	/**
	 * 加载Logic对象
	 * @param string $logic Logic文件夹下的文件名
	 * */
	protected function Logic($logic = 'UserLogic') {
        return Tin::loadModule(Module::LOGIC, $logic);
    }
    /** 返回指定类型的数据
     * @param $data 数组数据
     * @param $type 返回数据格式 json/xml，默认json
     * @param $rootname XML首节点的名称,默认DATA
     *  */
    public static function getResources($data, $type='json', $rootname="DATA"){
    	if($type=="json"){
    		return json_encode($data);
    	}else{
    		return Xml::array2xml($data, $rootname);
    	}
    }
	/**
	 * 输出系统提示信息
	 * @param string $msg 提示文字
	 * @param array $urls 跳转URL数组 array("文字"=>"URL地址")
	 * @param int $timeout 自动跳转等待时间【等于0时不跳转】，默认0
	 * @param string $title 提示页面的标题
	 * @param string $tplname 应用模板名称，必须存与public目录下，默认redirect_msg
	 * @author zhangxilian 2013-8-3
	 * */
	public static function sysMessage($msg, $urls=array(), $timeout=0, $title="系统提示", $tplname="redirect_msg") {
		$urlList = array ();		
		if (empty ($urls)) {
			$urlList['返回上一页'] = 'javascript:history.go(-1)';
		} else {
			foreach ($urls as $k => $v) {
				if (empty ($k)) {
					$k = '返回上一页';
				}
				if (preg_match("/javascript/iS", $v) || $v == 'GOBACK') {
					$urlList[$k] = 'javascript:history.go(-1);';
				} else {
					$urlList[$k] = $v;
				}
			}
		}
		if (preg_match("/javascript/iS", current($urlList))) {
			$autourl = current($urlList);
		} else {
			$autourl = "window.location.href =\'" . current($urlList) . "\';";
		}
		$res = array();
		$res['message'] = $msg;
		$res['urlList'] = $urlList;
		$res['title'] = $title;
		$res['autourl'] = $autourl;
		$res['timeout'] = $timeout;		
		T::$tpl->set("res", $res);		
		T::$tplFile = 'public/'.$tplname;
		return false;
	}
	/**
	 * 构建URL地址
	 * @param array $arr 附加参数Array
	 * @param string $header 指定绝对地址，默认为当前路径
	 * */
	public static function getUrl($arr, $header = null) {
		$domain = $_REQUEST["domain"];
		$url = "";
		if ($arr != null && count($arr)>0) {
			foreach ($arr as $key => $value) {
				$url .= "&$key=$value";
			}
		}
		if ($domain) { $url .= "&domain=" . $domain;}
		if($url!="" && substr($url,0,1)=="&") $url = "?".substr($url,1);
		return $header . $url;
	}	
	/**
     * curl发送请求地址并获取结果
     * @param string $reqURI 远程地址
     * @param string $reqxml 请求提交的参数
     * @param string $errMsg out返回异常信息
     * @param string $http_Header 自定义HTTP请求头,String或Array
     * @return String
     */
    public function sendXMLRequest($reqURI, $reqxml, &$errMsg = "", $http_Header = null) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $reqURI);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		if($http_Header) curl_setopt($curl, CURLOPT_HTTPHEADER, $http_Header);
		curl_setopt($curl, CURLOPT_HEADER, FALSE);
		curl_setopt($curl, CURLOPT_POST, TRUE);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $reqxml);
		curl_setopt($curl, CURLOPT_TIMEOUT, "20");
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		$retdata = curl_exec($curl);
		if (curl_errno($curl)) {
			$errMsg = curl_error($curl);
			curl_close($curl);
			return NULL;
		}
		curl_close($curl);
		return $retdata;
	}









	/* suche-------------------------------------------------------------------
    生成随机数 */
    public function random($length, $chars = '0123456789') {
        $hash = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
    public function sendsms($mobile, $send_txt) {
        if(!preg_match('/^(?:13\d{9}|15[0|1|2|3|5|6|7|8|9]\d{8}|18[0|2|3|5|6|7|8|9]\d{8}|14[5|7]\d{8})$/',$mobile)) exit('mobile phone error');
        $result = file_get_contents('http://service.winic.org/sys_port/gateway/?id=fancaineng2433&pwd=fan48331310&to='.$mobile.'&content='.iconv('UTF-8', 'GB2312', $send_txt).'&time=');
        $resultarr =explode('/',$result);
        if ($resultarr[0]==000){
            echo 0;
        }else{
            echo $result;
        }
    }
    /**
     * 返回经addslashes处理过的字符串或数组
     * @param $string 需要处理的字符串或数组
     * @return mixed
     */
    function new_addslashes($string){
        if(!is_array($string)) return addslashes($string);
        foreach($string as $key => $val) $string[$key] = $this->new_addslashes($val);
        return $string;
    }

    /**
     * 返回经stripslashes处理过的字符串或数组
     * @param $string 需要处理的字符串或数组
     * @return mixed
     */
    function new_stripslashes($string) {
        if(!is_array($string)) return stripslashes($string);
        foreach($string as $key => $val) $string[$key] = $this->new_stripslashes($val);
        return $string;
    }

    /**
     * 返回经htmlspecialchars处理过的字符串或数组
     * @param $obj 需要处理的字符串或数组
     * @return mixed
     */
    function new_html_special_chars($string) {
        $encoding = 'utf-8';
        if(strtolower(CHARSET)=='gbk') $encoding = 'gb2312';
        if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
        foreach($string as $key => $val) $string[$key] = $this->new_html_special_chars($val);
        return $string;
    }

    function new_html_entity_decode($string) {
        $encoding = 'utf-8';
        if(strtolower(CHARSET)=='gbk') $encoding = 'gb2312';
        return html_entity_decode($string,ENT_QUOTES,$encoding);
    }
    /**
     * 安全过滤函数
     *
     * @param $string
     * @return string
     */
    function safe_replace($string) {
        $string = str_replace('%20','',$string);
        $string = str_replace('%27','',$string);
        $string = str_replace('%2527','',$string);
        $string = str_replace('*','',$string);
        $string = str_replace('"','&quot;',$string);
        $string = str_replace("'",'',$string);
        $string = str_replace('"','',$string);
        $string = str_replace(';','',$string);
        $string = str_replace('<','&lt;',$string);
        $string = str_replace('>','&gt;',$string);
        $string = str_replace("{",'',$string);
        $string = str_replace('}','',$string);
        $string = str_replace('\\','',$string);
        return $string;
    }

    /**
     * 过滤ASCII码从0-28的控制字符
     * @return String
     */
    function trim_unsafe_control_chars($str) {
        $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
        return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
    }

    /**
     * 格式化文本域内容
     *
     * @param $string 文本域内容
     * @return string
     */
    function trim_textarea($string) {
        $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
        return $string;
    }

    /**
     * 将文本格式成适合js输出的字符串
     * @param string $string 需要处理的字符串
     * @param intval $isjs 是否执行字符串格式化，默认为执行
     * @return string 处理后的字符串
     */
    function format_js($string, $isjs = 1) {
        $string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
        return $isjs ? 'document.write("'.$string.'");' : $string;
    }

    /**
     * 转义 javascript 代码标记
     *
     * @param $str
     * @return mixed
     */
     function trim_script($str) {
        if(is_array($str)){
            foreach ($str as $key => $val){
                $str[$key] = $this->trim_script($val);
            }
        }else{
            $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
            $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
            $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
            $str = str_replace ( 'javascript:', 'javascript：', $str );
        }
        return $str;
    }
    /**
    * 将字符串转换为数组
    *
    * @param    string  $data   字符串
    * @return   array   返回数组格式，如果，data为空，则返回空数组
    */
    function string2array($data) {
        if($data == '') return array();
       // echo $data;
         //$data = $this->new_addslashes($data);
        @eval("\$array = $data;");
        return $array;
    }
    /**
    * 将数组转换为字符串
    *
    * @param    array   $data       数组
    * @param    bool    $isformdata 如果为0，则不使用new_stripslashes处理，可选参数，默认为1
    * @return   string  返回字符串，如果，data为空，则返回空
    */
    function array2string($data, $isformdata = 1) {
        if($data == '') return '';
        if($isformdata) $data = $this->new_stripslashes($data);
        return var_export($data, TRUE);
    }
    /**
    * 格式化价格
    *
    * @param    string  $price   
    * @return   返回$price.00
    */
    function format_price($price)
    {
        return number_format($price,2);
    }


    /**
    * 查询龙付通余额
    *
    * @param    string  $username       用户名
    * @return   array   $dataArr        返回数组，如果，data为空，则返回空
    */
    function lft_money($username) {

        $key = TIN_LFT_KEY;
        $postArr = array();
        $postArr['method'] = 'queryUser';
        $postArr['username'] = $username;
        $postArr['systtime'] = date('YmdHis',time());
        $postArr['format'] = 'json';
        $postArr['sign'] =   MD5(urlencode($postArr['username'].$postArr['systtime'].$key));
        $datareturn = json_decode($this->sendXMLRequest(TIN_LFT_URL.'api/nyd',$postArr),true);
        if($datareturn['RESPONSE']['MSG'][0]['RET_CODE'][0]=='1'){
            $dataArr = array();
            $dataArr['MONEY'] = $datareturn['RESPONSE']['DATA'][0]['AVAILABLEAMOUNT'][0];
            $dataArr['MONEY_FROZEN'] = $datareturn['RESPONSE']['DATA'][0]['FROZENAMOUNT'][0];
            $dataArr['MONEY_TOTAL'] = $datareturn['RESPONSE']['DATA'][0]['BALANCE'][0];

            return $dataArr;
        }
    }

    /**
    * 龙付通转帐
    *
    * @param    string  $username    用户名
    * @param    string  $touser      转至用户名
    * @param    string  $money       转多少钱
    * @param    string  $remark      备注(投资，回收利息，回收本金)
    * @return   array   $dataArr      返回数组，如果，data为空，则返回空
    */
    function lft_transfer($username,$touser,$money,$remark) {
        $key = TIN_LFT_KEY;
        $postArr = array();
        $postArr['method'] = 'submitTransfer';
        $postArr['username'] = $username;
        $postArr['otherName'] = $touser;
        $postArr['facevalue'] = $money;
        $postArr['remark'] = '农易贷-'.$remark;
        $postArr['systtime'] = date('YmdHis',time());
        $postArr['format'] = 'json';
        $postArr['sign'] =  MD5(urlencode($postArr['username'].$postArr['otherName'].$postArr['facevalue'].$postArr['remark'].$postArr['systtime'].$key));
        //echo $this->sendXMLRequest(TIN_LFT_URL.'api/nyd',$postArr);
        $datareturn = json_decode($this->sendXMLRequest(TIN_LFT_URL.'api/nyd',$postArr),true);
        print_r($datareturn);
        if($datareturn['RESPONSE']['MSG'][0]['RET_CODE'][0]==1){
            $logLogic = new LogsLogic();
            $postArr['lftid'] = $datareturn['RESPONSE']['MSG'][0]['RET_ID'][0];
            $infoid = $logLogic->addPayLog($postArr);

            return 1;
        }

    }
} //End Class
?>
